package userserv

import (
	"errors"
	"github.com/garyburd/redigo/redis"
	"log"
	"rhelper"
	"strconv"
)

func convertString2Int(val string) int {
	if val == "" {
		return 0
	}

	i, err := strconv.Atoi(val)
	if err != nil {
		// handle error
		log.Println("can't convert string to int")
		return 0
	}

	return i
}

func convertUser2Account(user string) (string, error) {
	rconn := rhelper.Pool().Get()
	defer rconn.Close()
	account, err := redis.String(rconn.Do("HGET", rhelper.UserHash+user, "account"))
	if err != nil {
		return "", err
	}
	if len(account) == 0 {
		return "", errors.New("User not exist.")
	}
	return account, nil
}

func convertAccount2User(account string) (string, error) {
	rconn := rhelper.Pool().Get()
	defer rconn.Close()
	user, err := redis.String(rconn.Do("HGET", rhelper.AccountHash+account, "id"))
	if err != nil {
		return "", err
	}
	if len(user) == 0 {
		return "", errors.New("account not exist.")
	}
	return user, nil
}

func getUserInfoById(userId string) ([]string, error) {
	rconn := rhelper.Pool().Get()
	defer rconn.Close()

	defaultHeadPortrait := "CD466A0ABAE6B5C0.png"
	host := "http://198.211.33.183:4002/headPortrait?img="

	userInfo, err := redis.Strings(rconn.Do("HMGET", rhelper.UserHash+userId, "nickname", "headportrait"))

	if err != nil {
		return nil, err
	}

	if len(userInfo[0]) == 0 {
		userInfo[0] = userId

	}

	if len(userInfo[1]) == 0 {
		userInfo[1] = host + defaultHeadPortrait
	} else {
		userInfo[1] = host + userInfo[1]
	}

	return userInfo, nil
}
